package com.ruoyi.web.controller.account;



import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.config.MiniProgramConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysAccount;
import com.ruoyi.system.service.ISysAccountService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户管理Controller
 *
 * @author ruoyi
 * @date 2021-11-18
 */
@RestController
@RequestMapping("/system/account")
public class SysAccountController extends BaseController
{
    @Autowired
    private ISysAccountService sysAccountService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAccount sysAccount)
    {
        startPage();
        List<SysAccount> list = sysAccountService.selectSysAccountList(sysAccount);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping("/listofrepair")
    public TableDataInfo listofrepair(SysAccount sysAccount)
    {


        sysAccount.setAccountRolename("1");
        sysAccount.setAccountStatus("0");
        startPage();
        List<SysAccount> list = sysAccountService.selectSysAccountList(sysAccount);
        System.out.println(list);
        return getDataTable(list);
    }









    /**
     * 导出用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysAccount sysAccount)
    {
        List<SysAccount> list = sysAccountService.selectSysAccountList(sysAccount);
        ExcelUtil<SysAccount> util = new ExcelUtil<SysAccount>(SysAccount.class);
        return util.exportExcel(list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:account:query')")
    @GetMapping(value = "/{accountId}")
    public AjaxResult getInfo(@PathVariable("accountId") Integer accountId)
    {
        return AjaxResult.success(sysAccountService.selectSysAccountByAccountId(accountId));
    }

    /**
     * 新增用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAccount sysAccount)
    {
        return toAjax(sysAccountService.insertSysAccount(sysAccount));
    }

    /**
     * 修改用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAccount sysAccount)
    {
        return toAjax(sysAccountService.updateSysAccount(sysAccount));
    }

    /**
     * 删除用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{accountIds}")
    public AjaxResult remove(@PathVariable Integer[] accountIds)
    {
        return toAjax(sysAccountService.deleteSysAccountByAccountIds(accountIds));
    }


    @PostMapping("/login")
    public String Login(@RequestBody JSONObject req){
        String accountPhone =req.getString("accountPhone");
        String accountPassword =req.getString("accountPassword");
        System.out.println(accountPhone);
        System.out.println(accountPassword);
//        Objects.requireNonNull(accountPhone,"账号为空");
        SysAccount sysAccount = sysAccountService.selectSysAccountByAccountPhone(accountPhone);
        if (sysAccount==null){
            return "noregister";
        }else if (sysAccount!=null&sysAccount.getAccountPassword().equals(accountPassword)){
            return "success";

        }else {
            return "pswerror";
        }



    }


    @RequestMapping("/register")
    @ResponseBody
    public Object register(String code,String phone,String password,String name){

        //号码是否存在
        SysAccount sysAccountexist = sysAccountService.selectSysAccountByAccountPhone(phone);
        if (sysAccountexist!=null){
            return "exist";
        }

        try {
            System.out.println(2);
            CloseableHttpClient httpClient = HttpClients.createDefault();      //导入小程序配置类下面
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+ MiniProgramConfig.appid+"&secret="+MiniProgramConfig.secret+"&js_code="+code+"&grant_type=authorization_code";
            HttpGet get =new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(get);
            String result = EntityUtils.toString(response.getEntity(),"utf-8");
            JSONObject json =JSONObject.parseObject(result);
            if (!json.containsKey("errcode")){
                String openid = json.getString("openid");

                //该小程序账号是否注册
                SysAccount sysAccountexisttwo = sysAccountService.selectSysAccountByAccountOpenid(openid);
                if (sysAccountexisttwo!=null){
                    return "openidexist";
                }

                //存数据库
                SysAccount sysAccount =new SysAccount();
                sysAccount.setAccountOpenid(openid);
                sysAccount.setAccountPhone(phone);
                sysAccount.setAccountName(name);
                sysAccount.setAccountPassword(password);
                sysAccount.setAccountRolename("0");
                sysAccount.setAccountStatus("0");
                System.out.println(openid);
                sysAccountService.insertSysAccount(sysAccount);

                return "success";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "error";

    }


    //查询电话号码是否注册

    @PostMapping("/isregister")
    public int isRegister(String phone){
        System.out.println(115135);
        SysAccount sysAccount = sysAccountService.selectSysAccountByAccountPhone(phone);
        if (sysAccount!=null){
            return 1;
        }else return 0;


    }

    //查询账号的角色

    @RequestMapping("/rolename")

    public String getRolename(String phone){

        SysAccount sysAccount = sysAccountService.selectSysAccountByAccountPhone(phone);
        String rolename =sysAccount.getAccountRolename();
        return rolename;
    }


    //号码查姓名

    @RequestMapping("/getnamebyphone")
    public String getNamebyphone(String phone){


         SysAccount sysAccount=    sysAccountService.selectSysAccountByAccountPhone(phone);

        return sysAccount.getAccountName();
    }

    //获取全部维修工
    @RequestMapping("/allrepair")
    public List<SysAccount> getAllrepair(SysAccount sysAccount){
        sysAccount.setAccountRolename("1");

        return sysAccountService.selectSysAccountList(sysAccount);




    }


    //获取小程序端全账号
    @RequestMapping("/all")
    public List<SysAccount> getAllaccount(SysAccount sysAccount){

        return sysAccountService.selectSysAccountList(sysAccount);

    }

    @RequestMapping("/tongJi")
    public Object tongJi(){
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> res = new HashMap<String, Object>();
        SysAccount sysAccount =sysAccountService.selectaccountNumber();
        SysUser sysUser =sysUserService.getUserNum();
        data.put("a",sysAccount);
        data.put("b",sysUser);

        return data;

    }




















}



























